<?php

namespace backend\models;

use Yii;
use common\helpers\Util;
use common\libs\Constants;
use common\models\Article as ArticleModel;
use common\models\ArticleContent;
use common\models\meta\ArticleMetaTag;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;

/**
 * Article represents the model behind the search form of `common\models\Article`.
 */
class Article extends ArticleModel
{

    const ARTICLE     = 0;
    const SINGLE_PAGE = 2;

    const ARTICLE_PUBLISHED = 1;
    const ARTICLE_DRAFT     = 0;

    /**
     * 需要截取的文章缩略图尺寸
     */
    public static $thumbSizes = [
        ["w" => 220, "h" => 150],//首页文章列表
        ["w" => 168, "h" => 112],//精选导读
        ["w" => 185, "h" => 110],//文章详情下边图片推荐
        ["w" => 125, "h" => 86],//热门推荐
    ];

    /**
     * @var string
     */
    public $tag = '';

    /**
     * @var null|string
     */
    public $content = null;

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function scenarios()
    {
        return ArrayHelper::merge(
            parent::scenarios(),
            [
                'article' => [
                    'article_category_id',
                    'type',
                    'title',
                    'sub_title',
                    'summary',
                    'content',
                    'thumb',
                    'seo_title',
                    'seo_keywords',
                    'seo_description',
                    'status',
                    'sort',
                    'author_id',
                    'author_name',
                    'scan_count',
                    'comment_count',
                    'can_comment',
                    'visibility',
                    'tag',
                    'flag_headline',
                    'flag_recommend',
                    'flag_slide_show',
                    'flag_special_recommend',
                    'flag_roll',
                    'flag_bold',
                    'flag_picture',
                    'password',
                ],
                'page'    => [
                    'cid',
                    'type',
                    'title',
                    'sub_title',
                    'summary',
                    'seo_title',
                    'content',
                    'seo_keywords',
                    'seo_description',
                    'status',
                    'flag_headline',
                    'can_comment',
                    'visibility',
                    'tag',
                    'sort',
                ],
            ]
        );
    }


    /**
     * @inheritdoc
     */
    public function afterValidate()
    {
        parent::afterValidate();
        if ($this->visibility == Constants::ARTICLE_VISIBILITY_SECRET) {//加密文章需要设置密码
            if (empty($this->password)) {
                $this->addError('password', yii::t('app', "Secret article must set a password"));
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function beforeSave($insert)
    {
        Util::handleModelSingleFileUpload($this, 'thumb', $insert, '@pathRoot/uploads/thumb/', ['thumbSizes' => self::$thumbSizes]);
        $this->seo_keywords = str_replace('，', ',', $this->seo_keywords);
        if ($insert) {
            $this->author_id   = yii::$app->getUser()->getIdentity()->getId();
            $this->author_name = yii::$app->getUser()->getIdentity()->username;
        }

        return parent::beforeSave($insert);
    }

    /**
     * @inheritdoc
     */
    public function afterSave($insert, $changedAttributes)
    {
        $articleMetaTag = new ArticleMetaTag();
        $articleMetaTag->setArticleTags($this->id, $this->tag);
        if ($insert) {
            $contentModel      = new ArticleContent();
            $contentModel->aid = $this->id;
        } else {
            if ($this->content === null) {
                return;
            }
            $contentModel = ArticleContent::findOne(['aid' => $this->id]);
            if ($contentModel == null) {
                $contentModel      = new ArticleContent();
                $contentModel->aid = $this->id;
            }
        }
        $contentModel->content = $this->content;
        $contentModel->save();
        parent::afterSave($insert, $changedAttributes);
    }

    /**
     * @inheritdoc
     */
    public function beforeDelete()
    {
//        Comment::deleteAll(['aid' => $this->id]);
//        if (($articleContentModel = ArticleContent::find()->where(['aid' => $this->id])->one()) != null) {
//            $articleContentModel->delete();
//        }

        return true;
    }

    /**
     * @inheritdoc
     */
    public function afterFind()
    {
        parent::afterFind();
        $this->tag     = call_user_func(
            function () {
                $tags = '';
                foreach ($this->articleTags as $tag) {
                    $tags .= $tag->value.',';
                }

                return rtrim($tags, ',');
            }
        );
        $this->content = ArticleContent::findOne(['aid' => $this->id])['content'];
    }

    public function attributeLabels()
    {
        return ArrayHelper::merge(
            parent::attributeLabels(),
            [
                'id'                     => '文章自增id',
                'article_category_id'    => '文章分类id',
                'type'                   => '类型.0文章,1单页',
                'title'                  => '文章标题',
                'sub_title'              => '副标题',
                'summary'                => '文章概要',
                'thumb'                  => '缩略图',
                'seo_title'              => 'seo标题',
                'seo_keywords'           => 'seo关键字',
                'seo_description'        => 'seo描述',
                'status'                 => '状态',//.0草稿,1发布
                'sort'                   => '排序',
                'author_id'              => '管理员id',//发布文章
                'author_name'            => '管理员',//发布文章用户名
                'scan_count'             => '浏览次数',
                'comment_count'          => '浏览次数',
                'can_comment'            => '评论',//是否可评论.0否,1是
                'visibility'             => '可见性',//文章可见性.1.公开,2.评论可见,3.加密文章,4.登陆可见
                'password'               => '文章明文密码',
                'flag_headline'          => '头条',//.0否,1.是
                'flag_recommend'         => '推荐',//.0否,1.是
                'flag_slide_show'        => '幻灯',//.0否,1.是
                'flag_special_recommend' => '特别推荐',//.0否,1.是
                'flag_roll'              => '滚动',//.0否,1.是
                'flag_bold'              => '加粗',//.0否,1.是
                'flag_picture'           => '图片',//.0否,1.是
                'created_at'             => '创建时间',
                'updated_at'             => '最后修改时间',
                'content'                => Yii::t('app', 'Content'),
            ]
        );

    }

}
